package net.projects.pro1_weather;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.logging.Logger;

public class NetServer {
    static Logger log = Logger.getLogger(NetServer.class.getName());

    public static void main(String[] args) throws IOException {
        // 创建服务端的对象
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(65201);
            log.info("已经绑定到端口" + ss.getLocalPort());
        } catch (IOException e) {
            log.severe("端口被占用");
            throw new RuntimeException(e);
        }

        // 等待数据
        Socket socket = null;
        BufferedWriter writer = null;
        while (true) {
            log.info("等待数据中");
            try {
                socket = ss.accept();
                // 设置超时时间为10秒（单位为毫秒）
                socket.setSoTimeout(3000);

                // 使用高速读写缓冲流
                BufferedReader bfd = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bfd.readLine()) != null) {
                    sb.append(line);
                }
                log.info("获取到用户数据为 " + sb);

                // 返回天气信息
                OutputStream os = socket.getOutputStream();
                writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));

                String city = sb.toString().trim().isEmpty() ? "BeiJing" : sb.toString(); // 默认为北京
                String reply = "This is " + city + "'s weather forecast for the next 5 days\n";
                writer.write(reply);

                List<String> weatherForecast = WeatherForecast.getweather(city);
                if (weatherForecast != null) {
                    for (int i = 0; i < weatherForecast.size(); i++) {
                        writer.write("Day " + (i + 1) + ": " + weatherForecast.get(i) + "\n");
                    }
                    writer.write("Data provided by openweathermap\n");
                    writer.flush(); // 刷新缓冲区，确保数据发送完整

                    log.info("数据返回成功");
                }
            } catch (SocketTimeoutException e) {
                // 客户端超时处理
                log.warning("客户端连接超时，返回默认天气信息");
                String city = "BeiJing"; // 默认为北京
                OutputStream os = socket.getOutputStream();
                writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
                String reply = "This is " + city + "'s weather forecast for the next 5 days\n";
                writer.write(reply);

                List<String> weatherForecast = WeatherForecast.getweather(city);
                if (weatherForecast != null) {
                    for (int i = 0; i < weatherForecast.size(); i++) {
                        writer.write("Day " + (i + 1) + ": " + weatherForecast.get(i) + "\n");
                    }
                    writer.write("Data provided by openweathermap\n");
                    writer.flush(); // 刷新缓冲区，确保数据发送完整

                    log.info("返回默认天气信息成功");
                }
            } catch (IOException e) {
                log.severe("IO异常: " + e.getMessage());
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException ex) {
                    log.severe("关闭连接出错: " + ex.getMessage());
                }
            }
        }
    }
}
